package com.atguigu.gulimall.gulimallmember.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.entity.SocialUser;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.gulimall.gulimallmember.entity.MemberLevelEntity;
import com.atguigu.gulimall.gulimallmember.exception.PhoneExistException;
import com.atguigu.gulimall.gulimallmember.exception.UsernameExistException;
import com.atguigu.gulimall.gulimallmember.vo.MemberLoginVo;
import com.atguigu.gulimall.gulimallmember.vo.RegisterVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.gulimallmember.dao.MemberDao;
import com.atguigu.gulimall.gulimallmember.entity.MemberEntity;
import com.atguigu.gulimall.gulimallmember.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(RegisterVo registerVo) {
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = new MemberEntity();

        MemberLevelEntity defaultLevel = memberDao.getDefaultLevel();
        memberEntity.setLevelId(defaultLevel.getId());

        checkPhoneUnique(registerVo.getPhone());
        memberEntity.setMobile(registerVo.getPhone());
        checkUsernameUnique(registerVo.getUsername());
        memberEntity.setUsername(registerVo.getUsername());

        // 密码加密存储，能通过加密字符串
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encodePassword = encoder.encode(registerVo.getPassword());
        memberEntity.setPassword(encodePassword);

        memberDao.insert(memberEntity);
    }

    @Override
    public void checkPhoneUnique(String phone) {
        MemberDao memberDao = this.baseMapper;
        Integer mobile = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobile > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public void checkUsernameUnique(String username) {
        MemberDao memberDao = this.baseMapper;
        Integer mobile = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (mobile > 0) {
            throw new UsernameExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo memberLoginVo) {
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = memberDao.selectOne(
                new QueryWrapper<MemberEntity>()
                        .eq("username", memberLoginVo.getLogincat())
                        .or()
                        .eq("mobile", memberLoginVo.getLogincat())
        );

        if (memberEntity == null) {
            return null;
        } else {
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            boolean matches = encoder.matches(memberLoginVo.getPassword(), memberEntity.getPassword());
            if (matches) {
                return memberEntity;
            } else {
                return null;
            }
        }
    }

    @Override
    public MemberEntity login(SocialUser socialUser) {
        String uid = socialUser.getUid();
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (memberEntity != null) {
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(socialUser.getAccess_token());
            update.setExpiresIn(socialUser.getExpires_in());
            memberDao.updateById(update);

            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(socialUser.getExpires_in());
            return memberEntity;
        } else {
            MemberEntity regist = new MemberEntity();

            try {
                Map<String, String> query = new HashMap<>();
                query.put("access_token", socialUser.getAccess_token());
                query.put("uid", socialUser.getUid());
                HttpResponse httpResponse = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<>(), query);
                if (httpResponse.getStatusLine().getStatusCode() == 200) {
                    String json = EntityUtils.toString(httpResponse.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);

                    String nickname = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");
                    regist.setNickname(nickname);
                    regist.setGender("m".equals(gender) ? 1 : 0);
                    // 其他信息
                }
            } catch (Exception e) { }

            regist.setSocialUid(socialUser.getUid());
            regist.setAccessToken(socialUser.getAccess_token());
            regist.setExpiresIn(socialUser.getExpires_in());
            memberDao.insert(regist);
            return regist;
        }
    }

}